<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          <span slot="before">共{{ total }}条记录</span>
        </template>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="List">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                slot="reference"
                v-fiximg="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmploye" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="obj">
              {{
                obj.row.timeOfEntry | formtDate
              }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{row}">
              <el-switch :value="row.enableState === 1" disabled />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button v-if="checkPermission('delEmployee')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageConfig.size"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 显示二维码 -->
      <el-dialog title="二维码" :visible.sync="isShowCodeDialog" @close="imgUrl=''">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
    <!-- 新添员工 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 角色管理 -->
    <assign-role
      ref="assignRole"
      :is-show-dialog.sync="isShowDialog"
      :user-id="userId"
    />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employee'
import Employee from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from './component/add-employee.vue'
import AssignRole from './component/assign-role.vue'
import QrCode from 'qrcode'

export default {
  components: { AddEmployee, AssignRole },
  // 局部过滤器
  filters: {
    formtDate(oldVal) {
      return oldVal.split('T')[0]
    }
  },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      List: [],
      total: 0,
      showDialog: false, // 点击显示新增员工框
      isShowDialog: false, // 角色管理
      userId: '',
      isShowCodeDialog: false,
      imgUrl: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // checkPermission(btnName) {
    //   return this.$store.state.user.userInfo.roles.points.includes(btnName)
    //   // return roles ? roles.points.includes(btnName) : false
    // },
    assignRole(id) {
      this.userId = id
      this.$refs.assignRole.getUserDetail(id)
      this.isShowDialog = true
    },
    // 点击头像显示二维码
    showQrCode(url) {
      console.log(113, url)
      // url存在的情况下 才弹出层
      if (url) {
        // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        this.isShowCodeDialog = true
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码

          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 删除员工接口
    async delEmployee(id) {
      await this.$confirm('是否删除')
      await delEmployee(id)
      this.$message.success('删除成功')
      // 如果本来剩下一条数据，删除后页码减一
      if (this.List.length === 1 && this.pageConfig.page > 1) {
        this.pageConfig.page--
      }
      this.getEmployeeList()
    },
    // 导出
    async exportExcel() {
      // 获取员工数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      console.log(rows)
      // 数据转换
      const data = rows.map(userObj => {
        return this.objToArray(userObj)
      })
      console.log(data)
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职时间']
      // 生成excel
      export_json_to_excel({
        header,
        data
      })
    },
    objToArray(userObj) {
      console.log(userObj)
      const userArray = []
      const zidian = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      }
      // 遍历字典, 每个key都拿出英文字段, 去用户对象获取数据
      // 推入数组中, 最终可以形成顺序的用户数组
      for (const key in zidian) {
        const enKey = zidian[key]
        const value = userObj[enKey]
        // 不一定全部都是直接push到数组中,
        // 如果发现正在处理聘用形式或者入职时间
        // 需要额外改造数据
        if (enKey === 'formOfEmployment') {
          const obj = Employee.hireType.find(item => Number(item.id) === Number(value))
          userArray.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry') {
          userArray.push(formatDate(value))
        } else {
          userArray.push(value)
        }
      }
      console.log(userArray)
      // 转换逻辑
      return userArray
    },
    // /---------------\
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageConfig)
      this.total = total
      // 本地数据库没有 enadleState 属性，可以考虑获取数据是手动造假的
      this.List = rows.map(user => {
        const state = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || state
        }
      })
    },
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.getEmployeeList()
    },
    formatEmploye(row, col, cellVal) {
      // return collVal === '1' ? '正式员工' : '非正式员工'

      // 将所有可能性，逐个逐个列举出来的数据
      // 叫做枚举数据
      const obj = Employee.hireType.find(item => Number(item.id) === Number(cellVal))
      return obj ? obj.value : ''
    }
  }
}
</script>

<style>
/* .app-container{
  padding: 0;
} */

</style>
